// const requestUrl = `http://47.104.106.10:9380`;
// const requestUrl = `https://qiche.zjysdb.com/dev-api`;
const requestUrl = `https://qiche.zjysdb.com/prod-api`;

/**
 *  @param {string} url 地址后缀
 *  @param {any} data 请求参数
 */
export function requsetGet(url, data) {
	return requset(url, 'GET', data);
}

export function requsetPost(url, data) {
	return requset(url, 'POST', data);
}
export function uploadImageOne(opt, successCallback, errorCallback) {
	if (typeof opt === 'string') {
		let url = opt;
		opt = {};
		opt.url = url;
	}
	let count = opt.count || 1,
		sizeType = opt.sizeType || ['compressed'],
		sourceType = opt.sourceType || ['album', 'camera'],
		is_load = opt.is_load || true,
		uploadUrl = opt.url || '',
		inputName = opt.name || 'file',
		fileType = opt.fileType || 'image';
	uni.chooseImage({
		count: count, //最多可以选择的图片总数  
		sizeType: sizeType, // 可以指定是原图还是压缩图，默认二者都有  
		sourceType: sourceType, // 可以指定来源是相册还是相机，默认二者都有  
		success: function(res) {
			//启动上传等待中...  
			uni.showLoading({
				title: '图片上传中'
			});
			// console.log(res.tempFilePaths[0], ' --------------》')
			uni.uploadFile({
				url: requestUrl + '/' + uploadUrl,
				filePath: res.tempFilePaths[0],
				fileType: fileType,
				name: inputName,
				formData: {
					'filename': inputName
				},
				header: {
					// #ifdef MP
					"Content-Type": "multipart/form-data",
					// #endif
					//[TOKENNAME]: 'Bearer ' + store.state.app.token
				},
				success: function(res) {
					uni.hideLoading();
					if (res.statusCode == 403) {
						uni.showToast({
							title: res.data,
							icon: 'none'
						})
					} else {
						let data = res.data ? JSON.parse(res.data) : {};
						if (data.code == 200) {
							successCallback && successCallback(data)
						} else {
							errorCallback && errorCallback(data);

							uni.showToast({
								title: data.msg,
								icon: 'none'
							})
						}
					}
				},
				fail: function(res) {
					uni.hideLoading();
					uni.showToast({
						title: '上传图片失败',
						icon: 'none'
					})
				}
			})
		}
	})
}

/**
 *  @param {get | set} type 使用类型
 *  @param {any} options 存储或修改
 */
export async function bindToken(type, options) {
	switch (type) {
		case 'set':
			uni.setStorage(options)
			break;
		case 'getToken':
			return await (() => {
				return new Promise((resolve) => {
					uni.getStorage({
						key: 'cyrappToken',
						success: ({
							data
						}) => {
							if (data) {
								resolve(data);
							} else {
								resolve({});
							}
						},
						fail: () => {
							resolve({});
						}
					})
				})
			})();
	}
}

function requset(url, method, data) {
	const suffix = url.indexOf('/') != -1 ? `/${url}` : url;
	let prefix = requestUrl + suffix;

	return new Promise(async (resolve, reject) => {
		const bindValue = await bindToken('getToken');
		uni.request({
			url: prefix,
			method,
			data,
			header: {
				'cyrappToken': bindValue?.cyrappToken,
				'content-type': 'application/x-www-form-urlencoded'
			},
			success(res) {
				if (res.data.code === 200) {
					resolve(res.data);
				} else {
					uni.clearStorage();
					reject(res.data.msg);
				}
			},
			fail(err) {
				console.error(err);
				reject(err.errMsg);
			}
		})
	})
}